//
// Created by 74354 on 2022/1/1.
//

#ifndef MYODRIVE_ENCODE_H
#define MYODRIVE_ENCODE_H

#include <stdint.h>
#include "main.h"
#define PI_          3.1415926535897932385
#include "cmsis_os.h"
class Encoder_t {
public:
    typedef enum {
        Incremental_AB = 0,    // 增量式编码器
        Incremental_ABZ = 1,
        AbsoluteValue = 2
    }EncoderType_t;

    struct ENC_Config{
        odTIM timer;
        EncoderType_t type;
        uint32_t _cpr;

    };

    odTIM encoder_timer{};
    EncoderType_t EncoderType;
    Encoder_t(){};
    unsigned int cpr{};  // count per revolution
    float speedRevolve{};         // [rad/s]
    bool zPhaseAround = false;

    void config(ENC_Config* config){EncoderType = config->type;cpr = config->_cpr;encoder_timer = config->timer;}

    uint16_t (*getCount)(){};
    int getCircleCount() const { return circleCount;}
    float getRadian() const{return PI_*2*((float)getCircleCount() + (float)getCount()/cpr);}
    float getAngle() const{return  360 * ((float)getCircleCount() + (float)getCount()/cpr);}
    float getSpeedRad() const{float start = getRadian();osDelay(50);return (getRadian() - start)*20.f;}

    void setCount(uint16_t value) const{encoder_timer.Instance->CNT = value;}
    void setCircleCount(int value){circleCount = value;}
    void resetZeroPos(){encoder_timer.Instance->CNT = 0;circleCount = 0;}
private:
    int circleCount = 0;

};




#endif //MYODRIVE_ENCODE_H
